package com.joker.utils;

import com.joker.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author JokerKS
 * @Date 2022/01/14 11:13
 * @Version 1.0
 */
@Component
public class HtmlParseUtil {
	// public static void main(String[] args) throws Exception {
	// 	new HtmlParseUtil().parseJD("你好").forEach(System.out::println);
	// }

	public List<Content> parseJD(String keywords) throws Exception {

		String url = "https://search.jd.com/Search?keyword=" + keywords;

		Document document = Jsoup.parse(new URL(url), 30000);
		Element element = document.getElementById("J_goodsList");
		Elements elements = element.getElementsByTag("li");

		List<Content> list = new ArrayList<>();
		for (Element el : elements) {
			String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");  // 获取li下 第一张图片
			String price = el.getElementsByClass("p-price").eq(0).text();
			String title = el.getElementsByClass("p-name").eq(0).text();
			Content content = new Content();
			content.setTitle(title);
			content.setImg(img);
			content.setPrice(price);
			list.add(content);
		}

		return list;
	}
}
